package com.second.hand.trading.server.model;

import com.second.hand.trading.server.service.Operlog;
import com.second.hand.trading.server.service.OperlogService;
import com.second.hand.trading.server.service.impl.OperlogServiceImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Component
@Aspect
public class Aop {
    @Pointcut("@annotation(com.second.hand.trading.server.service.Operlog)")
    public void aspect() {
    }
    @Autowired(required = false)
    private OperlogService op;

    @AfterReturning(value = "aspect()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        LogModel operlog = new LogModel();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            Operlog opLog = method.getAnnotation(Operlog.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                String object= opLog.object();
                operlog.setOperModul(operModul); // 操作模块
                operlog.setOperType(object); // 操作类型
                operlog.setOperDesc(operDesc); // 操作描述
            }
                String id = "";
                if (Objects.equals(opLog.object(), "用户")) {
                    Cookie[] cookies = request.getCookies();
                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if ("shSalesmanId".equals(cookie.getName())) { // 检查cookie的名称是否为"role"
                                id = cookie.getValue(); // 获取cookie的值
                                break; // 找到后退出循环
                            }
                        }
                    }
                } else if (Objects.equals(opLog.object(), "销售员")) {
                    Cookie[] cookies = request.getCookies();
                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if ("shUserId".equals(cookie.getName())) { // 检查cookie的名称是否为"role"
                                id = cookie.getValue(); // 获取cookie的值
                                break; // 找到后退出循环
                            }
                        }
                    }
                } else {
                    id = String.valueOf( request.getSession().getAttribute("admin"));

                }
                operlog.setUserName(id);

                SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                Calendar ca =Calendar.getInstance();
                String operDate = df.format(ca.getTime());
                operlog.setTime(operDate);
// ip
                String ip = getIp(request);
                ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
                operlog.setIp(ip);
            String result = "1";
            operlog.setOperResult(result);
            System.out.println(operlog.toString());

            op.addlog(operlog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取请求ip
     * @param request http请求
     * @return ip
     */
    public static String getIp(HttpServletRequest request){
        if(request.getHeader("x-forwarded-for") == null){
            return request.getRemoteAddr();
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    }



